import random
import hashlib#用于哈希加密MD5
from urllib import request
import json

def getTrans(in_word):
    fromLang = 'auto'  # 翻译源语言=自动检测
    toLang1 = 'auto'  # 译文语言 = 自动检测

    salt = random.randint(32768, 65536)
    appid = '20181130000241566'#百度APP ID：20181130000241566
    secretKey = 'nahb7SNM0KEG9VplL1t2'#密钥：nahb7SNM0KEG9VplL1t2
    sign = appid + in_word + str(salt) + secretKey#20181130000241566apple46230nahb7SNM0KEG9VplL1t2
    sign1=sign.encode('utf-8')#将文本转化为字节
    #b'20181130000241566apple56775nahb7SNM0KEG9VplL1t2'
    m1 = hashlib.md5(sign1)#进行哈希加密
    sign = m1.hexdigest()#加密生成新的值

    myurl = '/api/trans/vip/translate'
    myurl = myurl + '?appid=' + appid + '&q=' + in_word + '&from=' + fromLang + '&to=' + toLang1 + '&salt=' + str(
        salt) + '&sign=' + sign
    url = "http://api.fanyi.baidu.com" + myurl
    
    data = request.urlopen(url).read()#request.urlopen()内不能用字节格式，用字符串str格式
    data = json.loads(data)#利用json对b'{"from":"en","to":"zh","trans_result":
    #[{"src":"apple","dst":"\\u82f9\\u679c"}]}'进行下载
    
    data=data['trans_result'][0]['dst']
    return data#返回最后一个翻译的单词的中文释义
   
